<template>
  <div class="dish-page">
    <div class="dish-container">
      <!-- 左侧分类 -->
      <div class="category-sidebar">
        <h3>菜品类别</h3>
        <el-menu
          :default-active="activeCategory"
          class="category-menu"
          @select="handleCategorySelect"
        >
          <el-menu-item index="all">
            <span>全部</span>
          </el-menu-item>
          <el-menu-item index="stir-fry">
            <span>热菜</span>
          </el-menu-item>
          <el-menu-item index="steamed">
            <span>汤羹</span>
          </el-menu-item>
          <el-menu-item index="cold">
            <span>凉菜</span>
          </el-menu-item>
          <el-menu-item index="staple-food">
            <span>主食</span>
          </el-menu-item>
          <el-menu-item index="seafood">
            <span>海鲜</span>
          </el-menu-item>
        </el-menu>
      </div>

      <!-- 右侧内容 -->
      <div class="main-content">
        <!-- 查询和操作栏 -->
        <div class="action-bar">
          <div class="search-section">
            <el-input
              v-model="searchKeyword"
              placeholder="请输入要查询的菜品编号"
              prefix-icon="Search"
              clearable
              style="width: 300px"
            />
          </div>


          <div class="operation-buttons">
<!--            <el-button type="warning" @click="setPreSaleQuantity">预销量</el-button>-->
            <el-button type="danger" @click="stopSelling">停售</el-button>
            <el-button type="success" @click="startSelling">开售</el-button>
          </div>


        </div>

        <!-- 菜品表格 -->
        <div class="dish-table">
          <el-table
            :data="filteredDishes"
            border
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="dishId" label="ID" width="80" />
            <el-table-column prop="code" label="菜品编号" width="150" />
            <el-table-column prop="name" label="菜品名称" />
            <el-table-column prop="cname" label="菜品类别" width="120" />
            <el-table-column prop="uname" label="菜品单位" width="100" />
            <el-table-column prop="basePrice" label="售价" width="100">
              <template #default="scope">
                ¥{{ scope.row.basePrice }}
              </template>
            </el-table-column>
            <el-table-column prop="currentStock" label="剩余数量" width="120" />
            <el-table-column prop="isOnSale" label="状态" width="100">
              <template #default="scope">
                <el-tag
                  :type="getStatusType(scope.row.isOnSale)"
                  size="small"
                >
                  {{ getStatusText(scope.row.isOnSale) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 15, 20]"
            :total="totalDishes"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 预销量设置弹窗 -->
<!--    <el-dialog-->
<!--      v-model="preSaleDialogVisible"-->
<!--      title="设置预销量"-->
<!--      width="400px"-->
<!--    >-->
<!--      <el-form :model="preSaleForm" label-width="100px">-->
<!--        <el-form-item label="预销量:">-->
<!--          <el-input-number-->
<!--            v-model="preSaleForm.quantity"-->
<!--            :min="0"-->
<!--            :max="999"-->
<!--            placeholder="请输入预销量"-->
<!--          />-->
<!--        </el-form-item>-->
<!--      </el-form>-->

<!--      <template #footer>-->
<!--        <span class="dialog-footer">-->
<!--          <el-button @click="preSaleDialogVisible = false">取消</el-button>-->
<!--          <el-button type="primary" @click="confirmPreSale">确定</el-button>-->
<!--        </span>-->
<!--      </template>-->
<!--    </el-dialog>-->


  </div>
</template>

<script setup>
import {ref, computed, onMounted, watch} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from "axios";
import { debounce } from 'lodash'

const activeCategory = ref('all')
const searchKeyword = ref()
const currentPage = ref(1)
const pageSize = ref(10)
const selectedDishes = ref([])
const totalDishes = ref(0)

// 弹窗控制
// const preSaleDialogVisible = ref(false)


// 表单数据
const preSaleForm = ref({
  quantity: 0
})


// 菜品数据
const dishes = ref([])

// 查询
function findPage() {
  axios({
    url: '/api/dishManagement/listDishManagement',
    method: 'post',
    data: {
      current: currentPage.value,
      size: pageSize.value,
      code: searchKeyword.value,
    }
  }).then(response => {
    if (response.data.code === 200){
      dishes.value = response.data.data.records
      totalDishes.value = response.data.data.total
    }
  })
}

findPage()

// 监听搜索关键字变化，触发防抖查询
watch(searchKeyword, debounce((newVal, oldVal) => {
  currentPage.value = 1
  findPage()
}, 500))


// 计算属性
const filteredDishes = computed(() => {
  let filtered = dishes.value

  if (activeCategory.value !== 'all') {
    filtered = filtered.filter(dish => dish.cname === getCategoryText(activeCategory.value))
  }

  return filtered
})


// 方法
const handleCategorySelect = (key) => {
  activeCategory.value = key
  currentPage.value = 1
}

const handleSelectionChange = (selection) => {
  selectedDishes.value = selection
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  findPage()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  findPage()
}



// const setPreSaleQuantity = () => {
//   if (selectedDishes.value.length === 0) {
//     ElMessage.warning('请先选择要设置预售量的菜品')
//     return
//   }
//
//   const hasSoldOut = selectedDishes.value.some(dish => dish.isOnSale === false)
//   if (hasSoldOut) {
//     ElMessage.warning('停售的商品不能设置预销量')
//     return
//   }
//
//   preSaleForm.value.quantity = 0
//   preSaleDialogVisible.value = true
// }



const stopSelling = async () => {
  if (selectedDishes.value.length === 0) {
    ElMessage.warning('请先选择要停售的菜品')
    return
  }

  try {
    await ElMessageBox.confirm('确定要停售选中的菜品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 调用后端接口逐个停售菜品
    const promises = selectedDishes.value.map(dish => {
      return axios({
        url: '/api/dishManagement/stopDish',
        method: 'post',
        data: {
          dishId: dish.dishId
        }
      })
    })

    // 等待所有请求完成
    const results = await Promise.all(promises)

    // 检查所有请求是否都成功
    const allSuccess = results.every(result => result.data.code === 200)

    if (allSuccess) {
      // 更新前端数据状态
      selectedDishes.value.forEach(dish => {
        dish.isOnSale = false
      })

      ElMessage.success('菜品已停售')
    } else {
      ElMessage.error('部分菜品停售失败')
    }

    selectedDishes.value = []
    findPage()
  } catch (error) {
    // 用户取消或请求失败
    if (error !== 'cancel') {
      ElMessage.error('停售操作失败')
      findPage()
    }
  }
}

const startSelling = async () => {
  if (selectedDishes.value.length === 0) {
    ElMessage.warning('请先选择要开售的菜品')
    return
  }

  try {
    await ElMessageBox.confirm('确定要开售选中的菜品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 调用后端接口逐个开售菜品
    const promises = selectedDishes.value.map(dish => {
      return axios({
        url: '/api/dishManagement/startDish',
        method: 'post',
        data: {
          dishId: dish.dishId
        }
      })
    })

    // 等待所有请求完成
    const results = await Promise.all(promises)

    // 检查所有请求是否都成功
    const allSuccess = results.every(result => result.data.code === 200)

    if (allSuccess) {
      // 更新前端数据状态
      selectedDishes.value.forEach(dish => {
        dish.isOnSale = true
      })

      ElMessage.success('菜品已开售')
    } else {
      ElMessage.error('部分菜品开售失败')
    }

    selectedDishes.value = []
    findPage()
  } catch (error) {
    // 用户取消或请求失败
    if (error !== 'cancel') {
      ElMessage.error('开售操作失败')
      findPage()
    }
  }
}


const getStatusType = (isOnSale) => {
  switch (isOnSale) {
    case true:
      return 'success'
    case false:
      return 'danger'
    default:
      return ''
  }
}

const getStatusText = (isOnSale) => {
  switch (isOnSale) {
    case true:
      return '正常'
    case false:
      return '停售'
    default:
      return '未知'
  }
}


const getCategoryText = (category) => {
  switch (category) {
    case 'stir-fry':
      return '热菜'
    case 'steamed':
      return '汤羹'
    case 'cold':
      return '凉菜'
    case 'staple-food':
      return '主食'
    case 'seafood':
      return '海鲜'
    default:
      return ''
  }
}

onMounted(() => {
  // 初始化数据
})
</script>

<style scoped>
.dish-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.dish-container {
  flex: 1;
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  overflow: hidden;
}

.category-sidebar {
  width: 200px;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  height: fit-content;
}

.category-sidebar h3 {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 16px;
}

.category-menu {
  border-right: none;
}

.main-content {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.operation-buttons {
  display: flex;
  gap: 12px;
}

.dish-table {
  flex: 1;
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: center;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}


.instructions-box h4 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 16px;
}

.instructions-content p {
  margin: 8px 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
}
</style> 